package com.perfma.xtest.javassist;

import javassist.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 *
 *
 * @author: junhui.si
 * @date: 2024-08-06 14:50
 **/
public class JavassistDemo {
    public static void main(String[] args) throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        // 1
//        ClassPool classPool = ClassPool.getDefault();
//        CtClass ctClass = classPool.getCtClass("com.perfma.xtest.javassist.Student");
//        CtMethod ctMethod = ctClass.getDeclaredMethod("sayHello");
//        ctMethod.insertAfter("System.out.println(\"我是是你爹：\" + this.age);");
//
//        Class<Student> newClass = (Class<Student>) ctClass.toClass();
//        Student student = newClass.newInstance();
//        student.setAge(18);
//        student.setName("娘");
//        student.sayHello();

        // 2
        ClassPool classPool = ClassPool.getDefault();
        CtClass ctClass = classPool.getCtClass("com.perfma.xtest.javassist.Student");
        CtMethod ctMethod = new CtMethod(CtClass.intType, "calc", new CtClass[]{CtClass.intType, CtClass.intType}, ctClass);
        ctMethod.setModifiers(Modifier.PUBLIC);
        ctMethod.setBody("return $1 + $2;");
        ctClass.addMethod(ctMethod);
        ctClass.toClass();
        Student student = new Student();
        Method dMethod = Student.class.getDeclaredMethod("calc", new Class[]{int.class, int.class});
        Object result = dMethod.invoke(student, 10, 20);
        System.out.println(String.format("调用calc方法，传入参数：%d,%d", 10, 20));
        System.out.println("返回结果：" + (int) result);
    }
}
